package com.infotech.NginxMonitor.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CpuInfo {

	private static double cpuUsage = 0;
	private static long cpuTotal;
	private static long cpuIdle;

	public void refresh() {
		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(new File("/proc/stat")));
			String str = reader.readLine();
			reader.close();

			String[] array = str.split("\\s+");
			// unit: jiffies
			int total = Integer.parseInt(array[1]) + Integer.parseInt(array[2])
					+ Integer.parseInt(array[3]) + Integer.parseInt(array[4])
					+ Integer.parseInt(array[5]) + Integer.parseInt(array[6])
					+ Integer.parseInt(array[7]);
			int idle = Integer.parseInt(array[4]);

			cpuUsage = ((total - cpuTotal) / (idle - cpuIdle));

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static double getCpuUsage() {
		return cpuUsage;
	}

	public static long getCpuTotal() {
		return cpuTotal;
	}

	public static void setCpuTotal(long cpuTotal) {
		CpuInfo.cpuTotal = cpuTotal;
	}

	public static long getCpuIdle() {
		return cpuIdle;
	}

	public static void setCpuIdle(long cpuIdle) {
		CpuInfo.cpuIdle = cpuIdle;
	}
}
